<?php

namespace app\admin\controller\tongcheng;

use addons\tongcheng\library\WebSocketService;
use app\admin\model\tongcheng\SystemConfigModel;
use app\admin\model\tongcheng\UserAddressModel;
use app\common\controller\Backend;
use think\Db;
use think\Env;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 骑手管理
 *
 * @icon fa fa-circle-o
 */
class Rider extends Backend
{
    protected $noNeedRight = ['online', 'multiset'];

    /**
     * RiderModel模型对象
     * @var \app\admin\model\tongcheng\RiderModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tongcheng\RiderModel;
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("workStatusList", $this->model->getWorkStatusList());
        $this->view->assign("workTypeList", $this->model->getWorkTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model
                ->with(['user', 'zone'])
                ->where($where);
            if ($user_ids = input('user_ids')) {
                $query->whereIn('user_id', $user_ids);
            }
            $list = $query->order($sort, $order)->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('zone')->visible(['name']);
            }

            // $result = array("total" => $list->total(), "rows" => $list->items());

            $total = $list->total();
            $rows  = $list->items();

            if (Env::get('app.preview', false)) {
                foreach ($rows as &$row) {
                    $row['mobile'] = UserAddressModel::hideUserMobile($row['mobile'] ?? '');
                }
            }

            $result = array("total" => $total, "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multiset($ids = null)
    {
        // if (false === $this->request->isPost()) {
        //     $this->error(__('Invalid parameters'));
        // }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (!$this->request->isPost()) {
            $this->view->assign("ids", $ids);
            return $this->view->fetch();
        }

        // if (false === $this->request->has('params')) {
        //     $this->error(__('No rows were updated'));
        // }
        // parse_str($this->request->post('params'), $values);
        // $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        // if (empty($values)) {
        //     $this->error(__('You have no permission'));
        // }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $day_first_take_deduct_fee = $params['day_first_take_deduct_fee'] ?? 0;
        $count                     = $this->model->whereIn('id', $ids)->update(['day_first_take_deduct_fee' => $day_first_take_deduct_fee]);
        // Db::startTrans();
        // try {
        //     // $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        //     // foreach ($list as $item) {
        //     //     $count += $item->allowField(true)->isUpdate(true)->save($values);
        //     // }
        //     Db::commit();
        // } catch (PDOException|Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 查看
     */
    public function online()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model
                ->with(['user', 'zone'])
                ->where($where);


            if ($user_ids = WebSocketService::getAllOnlineRider()) {
                $query->whereIn('user_id', $user_ids);
            }
            $list = $query->order($sort, $order)->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('zone')->visible(['name']);
            }

            // $result = array("total" => $list->total(), "rows" => $list->items());

            $total = $list->total();
            $rows  = $list->items();

            if (Env::get('app.preview', false)) {
                foreach ($rows as &$row) {
                    $row['mobile'] = UserAddressModel::hideUserMobile($row['mobile']);
                    if (!empty($row['user']['mobile'])) {
                        $row['user']['mobile'] = UserAddressModel::hideUserMobile($row['user']['mobile']);
                    }
                }
            }

            $result = array("total" => $total, "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 骑手地图
     */
    public function map()
    {
        // 地图key
        $map_key = SystemConfigModel::getValue('tx_map_key');
        if (!$map_key) {
            $this->error('未配置配置地图key，请先到【系统配置】-【配送相关配置】中配置地图key');
        }
        $this->view->assign('map_key', $map_key);

        if ($this->request->isAjax()) {
            $query = \addons\tongcheng\model\RiderModel::with([
                'user' => function ($query) {
                    $query->field('id,nickname,avatar');
                },
            ]);

            // 仅显示在线骑手
            $is_online = input('is_online/d', 0);
            if ($is_online) {
                $user_ids = WebSocketService::getAllOnlineRider();
                $query->whereIn('user_id', $user_ids);
            }

            // 工作状态
            $work_status = input('work_status', '');
            if ($work_status !== '') {
                $query->where('work_status', $work_status);
            }

            $riders = $query->select();
            if ($riders) {
                $riders = collection($riders)->toArray();
                foreach ($riders as &$rider) {
                    if (!empty($rider['user'])) {
                        // 处理头像链接
                        $rider['user']['avatar'] = !empty($rider['user']['avatar']) ? cdnurl($rider['user']['avatar']) : '';
                    }

                    if (Env::get('app.preview', false)) {
                        $rider['mobile'] = UserAddressModel::hideUserMobile($rider['mobile']);
                        if (!empty($rider['user']['mobile'])) {
                            $rider['user']['mobile'] = UserAddressModel::hideUserMobile($rider['user']['mobile']);
                        }
                    }
                }
            }

            $this->success('', null, $riders);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (Env::get('app.preview', false)) {
            if (!empty($row['user']['mobile'])) {
                $row['mobile'] = UserAddressModel::hideUserMobile($row['mobile']);
            }
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
